package com.trailwalker.javafx.core.fragment;

import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Trailwalker
 * @create 2021-09-05 17:55
 */
public class Fragment extends FragmentContext {

    private FragmentManager mFragmentManager;
    private Pane mContainerView;
    private Pane mContentView;
    private List<FragmentManager> mFragmentManagerList;

    @Override
    public void onCreate() {
        mFragmentManagerList = new ArrayList<>();
    }

    @Override
    public void startFragment(Class clz) {
        mFragmentManager.startFragment(clz);
    }

    @Override
    public void finish() {
        mContainerView.getChildren().clear();
        mFragmentManager.finish();
    }

    @Override
    public void setContainerView(Pane containerView) {
        mContainerView = containerView;
    }

    @Override
    public void setFragmentManager(FragmentManager fragmentManager) {
        mFragmentManager = fragmentManager;
    }

    @Override
    public void onRestart() {
        setContentView(mContentView);
    }

    public void addFragmentManager(FragmentManager fragmentManager) {
        fragmentManager.setActivity(getFragmentManager().getActivity());
        mFragmentManagerList.add(fragmentManager);
        if (fragmentManager.getMainFragment() != null) {
            fragmentManager.startFragment(fragmentManager.getMainFragment());
        }
    }

    public FragmentManager getFragmentManager() {
        return mFragmentManager;
    }

    public void setContentView(Pane contentView) {
        if (!mContainerView.getChildren().contains(contentView)) {
            mContentView = contentView;
            mContainerView.getChildren().clear();
            mContainerView.getChildren().add(mContentView);
            AnchorPane.setTopAnchor(mContentView, 0.0);
            AnchorPane.setRightAnchor(mContentView, 0.0);
            AnchorPane.setBottomAnchor(mContentView, 0.0);
            AnchorPane.setLeftAnchor(mContentView, 0.0);
        }
    }

    @Override
    public boolean onBackPressed() {
        boolean isHandled = false;
        for (int i = 0; i < mFragmentManagerList.size(); i++) {
            FragmentManager fragmentManager = mFragmentManagerList.get(i);
            if (fragmentManager.onBackPressed()) {
                isHandled = true;
            }
        }
        return isHandled;
    }
}
